package cn.hubujyjs.mooc.service.impl;

import cn.hubujyjs.mooc.exception.MoocException;
import cn.hubujyjs.mooc.service.OssService;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


@Service
public class OssServiceImpl implements OssService {

//    @Autowired
//    @Qualifier("ossClient")
//    private OSS oSSClient;

    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    @Value("${spring.cloud.alicloud.access-key}")
    String accessId ;

    @Value("${spring.cloud.alicloud.secret-key}")
    String accessKey ;

    // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
    @Value("${spring.cloud.alicloud.oss.endpoint}")
    String endpoint ;

    // 填写Bucket名称，例如examplebucket。
    @Value("${spring.cloud.alicloud.oss.bucket}")
    String bucket ;

    @Override
    public String uploadImage(MultipartFile file) {
        String path="img/";
        return upload(file,path);
    }

    @Override
    public String uploadVideo(MultipartFile file) {
        String path="video/";
        return upload(file,path);
    }

    public String upload(MultipartFile file,String path) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String now = format.format(date);
        String originalFilename = file.getOriginalFilename();
        String suffix;
        try {
            int i = originalFilename.lastIndexOf('.');
            suffix = originalFilename.substring(i);
        } catch (Exception e) {
            throw new MoocException(201, "上传的文件格式不正确");
        }
        String key =path +now + suffix;
        try {
            ossClient.putObject(bucket, key,file.getInputStream());
        } catch (IOException e) {
            throw new MoocException(201,"文件写入错误");
        }
        String url ="https://hjtblogpic.oss-cn-shanghai.aliyuncs.com/"+key;
        return url;
    }
}
